/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("KFInfo",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using Induction.IServices;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.Filters;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using System.Xml;

namespace Induction.Controllers
{
    [Route("api/KF")]
    public partial class KFInfoController
    {
        private readonly IKFInfoService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        
        [ActivatorUtilitiesConstructor]
        public KFInfoController(
            IKFInfoService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        readonly string ReceiveId = "ww9547a7ef95af08ac";
        readonly string Secret = "ERxw4Kf_nqoBS1ZWzp2OxxUT0Yine3uw_An-M4c3doE";
        readonly string Token = "7R8sdNdY68psFSWErqtPl";
        readonly string EncodingAESKey = "wMEy84mynCQUoTT4PbYbKzINHQ0xOAL6ILn3vFULn6N";

        /// <summary>
        /// 指令响应回调
        /// </summary>
        /// <returns></returns>
        [HttpGet, HttpPost, Route("CommandCallback"), AllowAnonymous]
        public async Task<IActionResult> CommandCallback(string msg_signature, string timestamp, string nonce, string echostr)
        {
            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(Token, EncodingAESKey, ReceiveId);
            int ret = 0;
            string sEchoStr = String.Empty;

            ret = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr, ref sEchoStr);

            if (ret != 0)
            {
                return Content("fail");
            }

            int a = 1;

            return Content(sEchoStr);
        }

        /// <summary>
        /// 获取消息
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("sync_msg"), AllowAnonymous]
        public async Task<IActionResult> sync_msg(string msg_signature, string timestamp, string nonce, string echostr, [FromBody] string sReqData)
        {

            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(Token, EncodingAESKey, ReceiveId);

            int ret = 0;
            string sMsg = String.Empty;

            ret = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, sReqData, ref sMsg);

            if (ret != 0)
            {
                return Content("fail");
            }

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sMsg);
            XmlNode root = doc.FirstChild;
            string content = root["Content"].InnerText;


            return Content(sMsg);
        }

    }
}
